package com.doyens.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.doyens.reggie.commons.BaseContext;
import com.doyens.reggie.commons.R;
import com.doyens.reggie.domain.AddressBook;
import com.doyens.reggie.service.AddressBookService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/addressBook")
@Slf4j
public class AddressBookController {
    @Autowired
    private AddressBookService addressBookService;

    // 查询当前登录用户的默认地址
    @GetMapping("default")
    public R<AddressBook> findDefaultAddressBook(){
        // 查询当前登录用户的默认地址
        LambdaQueryWrapper<AddressBook> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AddressBook::getUserId,BaseContext.getCurrentId());
        wrapper.eq(AddressBook::getIsDefault,1);
        AddressBook addressBook = addressBookService.getOne(wrapper);
        return R.success(addressBook);
    }

    // 设置默认地址
    @PutMapping("default")
    public R<String> setDefault(@RequestBody AddressBook addressBook){ // id
        addressBookService.setDefault(addressBook);
        return R.success("设置成功");
    }

    // 查询当前登录用户的收货地址
    @GetMapping("/list")
    public R<List<AddressBook>> list(){
        // 获取当前登录用户的id
        Long userId = BaseContext.getCurrentId();
        //
        LambdaQueryWrapper<AddressBook> wrapper =  new LambdaQueryWrapper<>();
        wrapper.eq(AddressBook::getUserId,userId);
        List<AddressBook> list = addressBookService.list(wrapper);
        return R.success(list);
    }

    // 添加地址
    @PostMapping
    public R<String> saveAddressBook(@RequestBody AddressBook addressBook){
        log.info("地址信息为：{}",addressBook);
        // 补齐当前登录用户的id userId
        addressBook.setUserId(BaseContext.getCurrentId());
        addressBookService.save(addressBook);
        return R.success("添加成功");
    }
}
